<script lang="ts" setup>
const themeColor: ITheme = themeStore().theme;
import { themeStore, ITheme } from "../store/modules/theme";
import {
  ComponentInternalInstance,
  getCurrentInstance,
  inject,
  onMounted,
  onUnmounted,
  reactive,
  watch,
  defineProps,
  provide,
} from "vue";
import { marked } from "marked";
import { List } from "vant";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const state = reactive({
  messageList: [],
  consultationList: [],
});
const emits = defineEmits(["listenPrintHtml"]);
const getFileDetails = (item: any) => {
  return new Promise((resolve) => {
    if (item.resourceFile && item.fileId) {
      let urls = item.resourceFile.split(",");
      let ids = item.fileId.split(",");
      let docList: any = [];
      for (let i = 0; i < urls.length; i++) {
        const url = urls[i];
        fetch(url, {
          method: "HEAD", // 只获取文件头部信息
        })
          .then((response) => {
            // 获取文件大小（Content-Length header）
            const fileSize = response.headers.get("Content-Length");
            // 从 URL 中提取文件名
            const fileName = url.substring(url.lastIndexOf("/") + 1);
            docList.push({
              fileName: fileName.includes('_') ? fileName.substring(0, fileName.lastIndexOf('_')) : fileName,
              fileSize: formatFileSize(Number(fileSize)),
              fileUrl: url,
              fileId: ids[i],
              fileType: fileName.split('.').pop().toLowerCase(),//文档类型
            });
            if (docList.length === urls.length) {
              resolve(docList)
            }
          })
          .catch((error) => {
            console.error("无法获取文件信息", error);
          });
      }
    }
  });
};

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return `${size} B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`;
  } else if (size < 1024 * 1024 * 1024) {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  } else {
    return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
  }
};

const getMessageList = (id: string) => {
  proxy?.$api
    .get(process.env.VUE_APP_BASE_API_URL + "/wechatApi/getSessionQAList", {
      requestId: id,
      sessionId: ''
    })
    .then(async (res: any) => {
      if (res.code === 200) {
        state.messageList = res.data;
        console.log(res.data);
        if (res.data[0].questionType === 4 || res.data[0].questionType === 1) {
          res.data.unshift({
            text: res.data[0].questionContent,
            type: 0
          });
        }
        if (res.data[0].questionType === 6) {
          res.data.unshift({
            text: res.data[0].questionContent,
            img: res.data[0].resourceFile,
            type: 6
          });
        }
        if (res.data[0].questionType === 7) {
          const list = await getFileDetails(res.data[0]); 
          res.data.unshift({
            text: res.data[0].questionContent,
            fileList: list,
            type: 7
          });
        }
        setOldSession(res.data);
      }
    });
};
const setOldSession = (data: any) => {
  let list = data;
  let classification: any = [];
  for (let j = 0; j < list.length; j++) {
    let i = list[j];
    if (i.type === 1 || i.questionType === 1) {
      let arr = i.classContent?.split("|") || [];
      for (let j = 0; j < arr.length; j++) {
        arr[j] = arr[j].replace(/all/g, "**联系人**");
        arr[j] = proxy?.$utils.phoneReg(arr[j], arr[j].requestId);
        let seconed = marked(arr[j]);
        arr[j] = seconed;
      }
      classification = arr;
      let html = i.answerContent;
      html = proxy?.$utils.phoneReg(html, i.requestId) || html;
      if (classification.length > 0) {
        i.classification = classification;
      }
      i.answerContent = marked(html);
      i.answerRaw = JSON.parse(i.answerRaw);
      i.printEnd = true;
      i.activeNames = [];
      i.activeNames1 = [];
    }
  }
  state.consultationList = list;
  console.log(state.consultationList);
  window.scrollTo(0, document.body.scrollHeight);
};
onMounted(() => {
  let params: any = proxy?.$utils.getUrlParam();
  proxy?.$utils.setCheckDomColor(".main-container", "background", "#F1F8FE");
  if (params.requestId) {
    getMessageList(params.requestId);
  }
  if (params.email) {
    themeStore().setCount(params.email || "");
  }
});
const isMobile = function () {
  const userAgent = navigator.userAgent.toLowerCase();
  return /iphone|ipod|android|windows phone|blackberry|bb10|mobi|xoom|tablet|mobile/i.test(
    userAgent
  );
};
const bindClick = (e: string) => {
  // localStorage.setItem('isPreview', JSON.stringify(true));
  // localStorage.setItem('sessionId', JSON.stringify(state.consultationList .length > 0 ?state.consultationList[0].sessionId : ''));
  if (isMobile()) {
    if (process.env.NODE_ENV === 'development') {

    } else if (process.env.NODE_ENV === 'test') {
      location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
    } else {
      location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
    }
  } else {
    if (process.env.NODE_ENV === 'development') {

    } else if (process.env.NODE_ENV === 'test') {
      location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
    } else {
      location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
    }
  }
}
</script>

<template>
  <div class="assistant-container">
    <div class="bg">
      <div class="top-con" id="top-con">
        <div class="header">
          <div class="header-name">
            <img @click="bindClick" :src="require('@/assets/images/robot1.png')" alt="">
            <span class="fs-16">爱小问</span>
          </div>
          <div class="button-content" @click="bindClick">
            和爱小问一起聊聊吧
          </div>
        </div>
      </div>
    </div>
    <div class="content consultation-mode" ref="scrollContainer">
      <div class="consultation-container">
        <div v-for="(item, index) in state.consultationList" :key="index">
          <div class="item itema" v-if="item.type === 0 || item.type === 6 || item.type === 7">
            <div class="con">
              <div class="con-text fs-16" v-html="item.text"></div>
            </div>
            <div class="img-qa" v-if="item.type === 6">
              <img :src="item.img" />
            </div>
            <div class="file-qa" v-if="item.type === 7">
              <div class="uploadImg">
                <div class="img" v-for="(i, index) in item.fileList" :key="index">
                  <!-- 文件缩略图 -->
                  <img class="img-thumbnail" src="@/assets/images/xleThumbnail.png" />
                  <!-- 文件描述 -->
                  <span class="img-info">
                    <div class="img-name">{{ i.fileName }}</div>
                    <div class="img-size">
                      <div>{{ i.fileType }}</div>
                      <div>{{ i.fileSize }}</div>
                    </div>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="item itemb" v-if="item.type === 1 || item.questionType">
            <div class="ai-icon">
              <img class="avatar" src="@/assets/images/robot1.png" />
              <span>爱小问</span>
            </div>
            <div class="con">
              <div class="con-text fs-16" v-html="item.answerContent"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bg {
  width: 1900px;
  background-size: cover;
  height: 60px;
  border-radius: 60px;
  margin: 10px auto;
  background: linear-gradient(152.42deg,
      rgba(92, 178, 255, 1) 17.78%,
      rgba(255, 177, 177, 1) 100%);
}

.assistant-container {
  background: #F1F8FE;
  height: 100vh;
  overflow: hidden;
}

.content {
  display: flex;
  width: 100%;
  margin-top: 24px;
  flex-direction: column;
  background: v-bind("themeColor.fillWhite");
  padding: 0 30px;
  border-radius: 24px;

  &.consultation-mode {
    background: none;
    padding: 0;
    border-radius: 0;
    border-radius: 20px;
    overflow-y: scroll;
    margin: 30px auto;
    z-index: 100;
    width: 1086px;
    height: 865px;
    position: relative;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .consultation-container {
    display: flex;
    flex-direction: column;

    .item.itemb {
      flex-direction: column;
      position: relative;

      .ai-icon {
        display: flex;
        align-items: center;
        margin-bottom: 24px;

        span {
          font-size: 16px;
          font-weight: 500;
          color: v-bind("themeColor.textColorGrey");
          line-height: initial;
          margin-left: 10px;
          vertical-align: bottom;
        }
      }

      .avatar {
        width: 30px;
        margin: 0;
      }

      .con {
        border-radius: 14px;
        background: v-bind("themeColor.fillWhite");
        box-shadow: 0px 0px 4px v-bind("themeColor.fillBlueLight");
      }
    }

    .item.itema {
      display: flex;
      flex-direction: column;
      justify-content: flex-end;

      .img-qa {
        text-align: right;
        width: 100%;
        overflow: hidden;

        img {
          max-width: 60%;
          /* 限制图片最大宽度为容器宽度 */
          max-height: 400px;
          /* 限制图片最大高度为400px */
          height: auto;
          /* 保持宽高比例 */
          width: auto;
          /* 保持宽高比例 */
          object-fit: contain;
          /* 保证图片自适应容器，且不会变形 */
          border-radius: 14px;
          padding: 14px 20px;
          background-color: rgba(92, 178, 255, 0.30);
        }
      }

      .file-qa {
        .uploadImg {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          justify-content: flex-end;
          margin-bottom: 14px;

          .img {
            width: 205px;
            height: 50px;
            padding: 10px;
            border-radius: 10px;
            position: relative;
            border: 1px solid #e7e7e7;
            background-color: #fff;
            display: flex;
            flex-direction: row;
            gap: 8px;

            .img-thumbnail {
              width: 30px;
              height: 30px;
              border-radius: 5px;
              object-fit: cover;
            }

            .img-info {
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              height: 100%;

              .img-name {
                color: #000;
                font-family: "PingFang SC";
                font-size: 12px;
                font-style: normal;
                font-weight: 400;
                max-width: 125px;
                line-height: normal;
                white-space: nowrap;
                /* 禁止换行 */
                overflow: hidden;
                /* 隐藏溢出的文本 */
                text-overflow: ellipsis;
                /* 添加省略号 */
              }

              .img-size {
                display: flex;
                gap: 5px;
                align-items: center;

                div {
                  color: #999;
                  font-family: "PingFang SC";
                  font-size: 10px;
                  font-style: normal;
                  font-weight: 400;
                  line-height: normal;
                }
              }
            }
          }
        }
      }

      .con {
        border-radius: 14px;
        margin: 30px 0 20px auto;
        background: rgba(92, 178, 255, 0.3);
        color: #333;
      }
    }

    .item {
      display: flex;
      justify-content: flex-end;
      margin-top: 40px;

      &:first-child {
        margin-top: 0;
      }

      .module-type {
        margin-top: 24px;

        span {
          margin-right: 24px;
          font-size: 28px;
          font-weight: 500;
          letter-spacing: 0px;
          line-height: 58px;
          color: rgba(148, 162, 176, 1);
          padding: 16px 50px;
          border-radius: 220px;
          background: rgba(240, 241, 242, 1);
        }

        span.active {
          background: rgba(219, 238, 255, 1);
          color: #5cb2ff;
        }
      }

      .avatar {
        margin-left: 16px;
        width: 51.6px;
        margin-right: 16px;
      }

      .con {
        max-width: 100%;
        display: flex;
        flex-direction: column;
        padding: 14px 20px;
        border-radius: 24px;
        color: v-bind("themeColor.textColor");
        // box-shadow: 0px 0px 8px v-bind("themeColor.shadowColor");
        font-size: 28px;
        overflow: hidden;

        .con-text {
          // display: flex;
          // flex-direction: column;
          // white-space: pre-wrap;
          overflow: hidden;

          ref{
            color: #999;
          }

          .docname {
            font-size: 24px;
            color: v-bind("themeColor.textColor");
          }

          span {
            font-size: 28px;
          }
        }

        .con-file {
          display: flex;
          flex-direction: column;

          margin-top: 20px;
          gap: 6px;

          .fromto {
            color: v-bind("themeColor.textColorLighten");
          }

          .file-item {
            margin: 4px 0px;
            word-break: break-all;
            color: v-bind("themeColor.textColor");

            &.active {
              color: #5cb2ff;
            }

            div:last-child {
              margin-top: 20px;
            }

            a {
              text-decoration: underline;
              color: #5cb2ff;
            }

            .iconfont {
              color: #5cb2ff;
              margin-right: 4px;
            }
          }
        }

        .con-opt {
          display: flex;
          justify-content: space-between;
          padding: 18px 0 0 0;

          .left {
            img {
              width: 36px;
              margin-right: 45px;
            }

            span {
              margin-left: 68px;

              &:first-child {
                margin-left: 0;
              }

              &.icon-good-a-copy,
              &.icon-quxiaodianzan-a-copy {
                color: #e97600;
              }
            }
          }

          .right {
            img {
              width: 36px;
              margin-left: 45px;
            }
          }
        }
      }

      &:nth-child(2n) {
        justify-content: flex-start;

        .avatar {
          margin-left: 16px;
        }
      }
    }
  }
}

.top-con {
  display: flex;
  align-content: center;
  height: 100%;
  margin: 0 10px 0 30px;

  .header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: 900;
    letter-spacing: 0px;
    z-index: 2;
    color: #ffffff;

    .header-name {
      display: flex;
      gap: 20px;

      img {
        width: 35px;
        object-fit: contain;
      }
    }

    &>div {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 40px;
    }

    .button-content {
      height: 70%;
      width: 240px;
      border-radius: 50px;
      background: #fff;
      color: #000;
      border: #F1F8FE 4px solid;
    }
  }
}
</style>
